
#import "AppDelegate.h"
#import "RootViewNavigationController.h"
#import "QiMingADXViewController.h"
#import <AppTrackingTransparency/AppTrackingTransparency.h>
#import <AdSupport/AdSupport.h>
#import <QiMingADXSDK/QiMingADXSDK.h>
#import <QiMingADXSDK/QiMingADXSplashAd.h>
#import <QiMingADKit/QiMingADKitMacros.h>
#import <QiMingADKit/UIColor+QiMingADKit.h>
#import <QiMingADXSDK/QiMingADXKitLogging.h>
#import "AdsPosId.h"
#import "QiMingAdxPrivacyViewController.h"
#import "QiMingPrivacyAlertView.h"

@interface AppDelegate ()<QiMingADXSplashAdDelegate>

@property (nonatomic ,strong) QiMingADXSplashAd  *splashAd;

@property (nonatomic, assign) NSTimeInterval time;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    _window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _window.rootViewController = [[RootViewNavigationController alloc] initWithRootViewController:[QiMingADXViewController new]];
    [_window makeKeyAndVisible];
    
    [self setThirtyPartySdk];
        
    return YES;
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // 热启动加载开屏广告 进入前台加载
    NSTimeInterval currentTime = [NSDate date].timeIntervalSince1970;
    if (self.time > 0 && (currentTime - self.time) > 30) {
        [self loadSplashAdView];
    }
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    self.time = [NSDate date].timeIntervalSince1970;
}

- (void)setThirtyPartySdk {
    if ([self isFirstAppLoad]) {
        [self showAgreePrivacy];
    }else {
        [self initQiMingSDK];
    }
}

- (void)initQiMingSDK {
    // 是否允许SDK采集设备信息（网络信息等） ，默认开启，如需关闭需在初始化之前设置(开启并不会影响审核)
    [QiMingADXSDK setEnablePersonalInformation:YES];
    [QiMingADXSDK setLogLevel:QiMingADXKitLogLevelDebug];
    //初始化QiMingADXSDK
    [QiMingADXSDK initWithAppId:normal_appId completionBlock:^(NSError * _Nullable error) {
        if (error){
            NSLog(@"初始化失败%@",error);
        }else{
            NSLog(@"初始化成功");
        }
    }];
    
    [self loadSplashAdView];
}

- (void)loadSplashAdView {
    CGFloat bottomViewHeight = [UIScreen mainScreen].bounds.size.height * 0.15;
    
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = [UIColor whiteColor];
    bottomView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, bottomViewHeight);
    UIImageView *logoImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"QiMingADX_Logo.png"]];
    logoImageView.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width-92)/2, (bottomViewHeight-36)/2, 92, 36);
    [bottomView addSubview:logoImageView];
    
    if (!_splashAd) {
        // 初始化开屏广告加载实例
        _splashAd = [[QiMingADXSplashAd alloc]init];
        // 开屏广告的posid
        _splashAd.posId = normal_splashAd_posId;
        // 开屏广告委托对象
        _splashAd.delegate = self;
        //设置默认启动图(一般设置启动图的平铺颜色为背景颜色，使得视觉效果更加平滑)
        _splashAd.backgroundColor = [UIColor qmad_getColorWithImage:[UIImage imageNamed:@"750x1334.png"] withNewSize:[UIScreen mainScreen].bounds.size];
    }
    // 加载并展示开屏广告
    [_splashAd loadAndShowInWindow:[UIApplication sharedApplication].keyWindow withBottomView:bottomView];
}

// 开屏广告回调方法
#pragma mark - QiMingADXSplashAdDelegate

/**
 *  开屏广告请求成功
 */
- (void)qimingadxSplashAdSuccessLoad:(QiMingADXSplashAd *)splashAd {
    
}

/**
 *  开屏广告素材加载成功
 */
- (void)qimingadxSplashAdDidLoad:(QiMingADXSplashAd *)splashAd {
    
}

/**
 *  开屏广告请求失败
 */
- (void)qimingadxSplashAdFailLoad:(QiMingADXSplashAd *)splashAd withError:(NSError *)error {
    _splashAd = nil;
    NSLog(@"splash开屏广告加载失败%@",error);
}
/**
 *  开屏广告展示失败
 */
- (void)qimingadxSplashAdRenderFaild:(QiMingADXSplashAd *)splashAd withError:(NSError *)error {
   
}

/**
 *  开屏广告曝光回调
 */
- (void)qimingadxSplashAdExposured:(QiMingADXSplashAd *)splashAd {
    
}

/**
 *  开屏广告点击回调
 */
- (void)qimingadxSplashAdClicked:(QiMingADXSplashAd *)splashAd {
    _splashAd = nil;
}

/**
 *  开屏广告关闭回调
 */
- (void)qimingadxSplashAdClosed:(QiMingADXSplashAd *)splashAd {
    
}


#pragma mark -- private

- (void)showAgreePrivacy {
    
    QiMingPrivacyAlertView *alertView = [[QiMingPrivacyAlertView alloc] init];
    __weak typeof(self) ws = self;
    [alertView setPrivacyBlock:^(NSString * _Nonnull privacyUrl) {
        __strong typeof(ws) self = ws;
        QiMingAdxPrivacyViewController *vc = [[QiMingAdxPrivacyViewController alloc] init];
        vc.url = privacyUrl;
        RootViewNavigationController *nav = [[RootViewNavigationController alloc] initWithRootViewController:vc];
        nav.modalPresentationStyle = UIModalPresentationFullScreen;
        [self.window.rootViewController presentViewController:nav animated:YES completion:nil];
    }];
    
    [alertView setCancelBlock:^{
        __strong typeof(ws) self = ws;
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"点击同意才能使用该App服务" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            [self showAgreePrivacy];
            }];
        [alert addAction:sure];
        [self.window.rootViewController presentViewController:alert animated:YES completion:nil];
        
    }];
    
    [alertView setConfirmBlock:^{
        __strong typeof(ws) self = ws;
        // 记录是否第一次启动
        [self writeAppLoad];
        // 获取idfa权限 建议启动就获取权限 不获取权限会影响收益
        if (@available(iOS 14.0, *)) {
            [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
                
            }];
        }
        // 用户同意隐私后 初始化
        [self initQiMingSDK];
    }];
    
    [alertView show];

}

#pragma mark -- helper

- (void)writeAppLoad {
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:@"yes" forKey:@"isFirstLoad"];
    [userDefault synchronize];
    
}

- (BOOL)isFirstAppLoad {

    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    if ([[userDefault objectForKey:@"isFirstLoad"] isEqualToString:@"yes"]) {
        return NO;
    }
    return YES;
    
}
@end
